package logic

import (
	"context"
	"doctor-medicine-system/mysql/models"
	"errors"

	"doctor-medicine-system/doctorrpc/doctorrpc"
	"doctor-medicine-system/doctorrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 登录
func (l *LoginLogic) Login(in *doctorrpc.LoginRequest) (*doctorrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	var doctor models.Doctor
	models.DB.Debug().Where("mobile = ?", in.Mobile).Find(&doctor)
	if doctor.ID == 0 {
		doctor = models.Doctor{
			Mobile:   in.Mobile,
			Password: in.Password,
		}
		models.DB.Debug().Create(&doctor)
	}

	if in.Password != doctor.Password {
		return nil, errors.New("密码错误,登录失败")
	}

	return &doctorrpc.LoginResponse{
		DoctorId: int64(doctor.ID),
	}, nil
}
